<?php
/**
 * 兼容第三方插件补丁文件
 * @appapi 兼容重整
 */
defined('BY_JYA') or exit('error');
$_AR['token'] = token();
define('IN_IA', true);
define('IA_ROOT', ROOT_D);
define('ATTACHMENT_ROOT', ROOT_AT);
$_W = $_AR;
$_W['attachurl'] = ATTACHMENT_URL;
$_W['acid'] = $_W['uniacid'] = $_W['weid'] = $_SESSION['uniacid'];
$_W['account']=$_SESSION['account'];
$_W['copyright'] = core_setting('site');
$_W['copyright']['llogo'] = $_W['copyright']['llogo'] ? tomedia($_W['copyright']['llogo']) : '../core/resource/images/ng-logo.png';
$_W['copyright']['icon'] = $_W['copyright']['icon'] ? tomedia($_W['copyright']['icon']) : '../core/resource/logoicon.png';
$_W['uid'] = $_SESSION['uid'];
$_W['openid'] = $_SESSION['openid'];
$_W['ispost'] = POST;
$_W['isajax'] = AJAX;
$_W['siteroot'] = SITEROOT;
if ($_SESSION['user']['type'] == 3 || $_SESSION['isfounder']) {
	$_W['role'] = 'manager';
} else {
	$role = pdo_getcolumn('uni_account_users', array('uid' => $_SESSION['uid']), 'role');
	$_W['role'] = $role ? $role : 'operator';
}
$_W['highest_role'] = 'owner';
$_W['timestamp'] = TIMESTAMP;
$_W['setting'] = core_setting();
$_W['config'] = config();
$_GPC = $_RQ;
class WeAccount {
	public static function create($uniacid = '') {
		if (!class_exists('account_wqz')) {
			require 'account_wqz.php';
		}
		;
		$return = new account_wqz();
		return $return;
	}
	public static function token() {
		return cfc('account')->getAccessToken();
	}
}
class WeiXinAccount {
	public static function create($uniacid = '') {
		if (!class_exists('account_wqz')) {
			require 'account_wqz.php';
		}
		;
		$return = new account_wqz();
		return $return;
	}
	public static function fetch_available_token($uniacid = '') {
		return cfc('account')->getAccessToken();
	}
}
function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
	return cfc('http')->ihttp_request($url, $post, $extra, $timeout);
}
function ihttp_get($url) {
	return cfc('http')->ihttp_request($url);
}
function ihttp_post($url, $data) {
	$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
	return cfc('http')->ihttp_request($url, $data, $headers);
}
function ihttp_email($to, $subject, $body, $global = false) {
	return cfc('http')->ihttp_email($to, $subject, $body, $global);
}
function file_write($filename, $data) {
	$filename = ATTACHMENT_ROOT . '/' . $filename;
	mkdirs(dirname($filename));
	file_put_contents($filename, $data);
	@chmod($filename, FILEMODE);
	return is_file($filename);
}
function file_move($filename, $dest) {
	mkdirs(dirname($dest));
	if (is_uploaded_file($filename)) {
		move_uploaded_file($filename, $dest);
	} else {
		rename($filename, $dest);
	}
	@chmod($filename, FILEMODE);
	return is_file($dest);
}
function mkdirs($path) {
	if (!is_dir($path)) {
		mkdirs(dirname($path));
		mkdir($path);
	}
	return is_dir($path);
}
function file_tree($path, $include = array()) {
	return cfc('files')->file_tree($path);
}
function file_copy($src, $des, $filter) {
	return cfc('files')->file_copy($src, $des);
}
function rmdirs($path, $clean = false) {
	return cfc('files')->rmdirs($path, $clean);
}
function file_delete($file) {
	if (empty($file)) {
		return false;
	}
	if (file_exists($file)) {
		@unlink($file);
	}
	if (file_exists(ATTACHMENT_ROOT . '/' . $file)) {
		@unlink(ATTACHMENT_ROOT . '/' . $file);
	}
	return true;
}
function file_lists($filepath, $subdir = 1, $ex = '', $isdir = 0, $md5 = 0, $enforcement = 0) {
	static $file_list = array();
	if ($enforcement) {
		$file_list = array();
	}
	$flags = $isdir ? GLOB_ONLYDIR : 0;
	$list = glob($filepath . '*' . (!empty($ex) && empty($subdir) ? '.' . $ex : ''), $flags);
	if (!empty($ex)) {
		$ex_num = strlen($ex);
	}
	foreach ($list as $k => $v) {
		$v = str_replace('\\', '/', $v);
        $v1 = str_replace(IA_ROOT . '/', '', $v);
        if ($subdir && is_dir($v)) {
            file_lists($v . '/', $subdir, $ex, $isdir, $md5);
            continue;
        }
        if (!empty($ex) && strtolower(substr($v, -$ex_num, $ex_num)) == $ex) {
            if ($md5) {
                $file_list[$v1] = md5_file($v);
            } else {
                $file_list[] = $v1;
            }
            continue;
        } elseif (!empty($ex) && strtolower(substr($v, -$ex_num, $ex_num)) != $ex) {
            unset($list[$k]);
            continue;
        }
    }
    return $file_list;
}
function iserializer($value) {
    return serialize($value);
}
function iunserializer($value) {
    if (empty($value)) {
        return array();
    }
    if (!is_serialized($value)) {
        return $value;
    }
    $result = unserialize($value);
    if ($result === false) {
        $temp = preg_replace_callback('!s:(d+):"(.*?)";!s', function ($matchs) {
            return 's:' . strlen($matchs[2]) . ':"' . $matchs[2] . '";';
        }, $value);
        return unserialize($temp);
    } else {
        return $result;
    }
}
function error1($errno, $message = '') {
    return array('errno' => $errno, 'message' => $message,);
}
function is_error1($data) {
    if (empty($data) || !is_array($data) || !array_key_exists('errno', $data) || (array_key_exists('errno', $data) && $data['errno'] == 0)) {
        return false;
    } else {
        return true;
    }
}
function setting_save($data = '', $key = '') {
    return core_setting($key, $data);
}
function is_serialized($data, $sdata = true) {
    $res= model('core/tools')->is_serialized($data,$sdata);
    return $res;
}
function setting_load($key) {
    $set = core_setting($key);
    $sett = array('site' => $set);
    return $sett;
}
function moduledata($params = '') {
    return '';
}
function template_modulehook_parser($params = array()) {
    return '';
}
function _calc_current_frames(&$frames) {
    return '';
}
function file_upload($file, $type = 'image', $name = '', $compress = false) {
    $harmtype = array('asp', 'php', 'jsp', 'js', 'css', 'php3', 'php4', 'php5', 'ashx', 'aspx', 'exe', 'cgi');
    if (empty($file)) {
        return error(-1, '没有上传内容');
    }
    if (!in_array($type, array('image', 'thumb', 'voice', 'video', 'audio'))) {
        return error(-2, '未知的上传类型');
    }
    global $_W;
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $ext = strtolower($ext);
    $setting = setting_load('upload');
    switch ($type) {
        case 'image':
        case 'thumb':
            $allowExt = array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'ico');
            $limit = $setting['upload']['image'];
        break;
        case 'voice':
        case 'audio':
            $allowExt = array('mp3', 'wma', 'wav', 'amr');
            $limit = $setting['upload']['audio'];
        break;
        case 'video':
            $allowExt = array('rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4');
            $limit = $setting['upload']['audio'];
        break;
    }
    if (!empty($setting['upload']['image_ext'])) {
        $setting['upload']['image_ext'] = explode(';', trim($setting['upload']['image_ext'], ';'));
        $allowExt = array_merge($setting['upload']['image_ext'], $allowExt);
    }
    if (!in_array(strtolower($ext), $allowExt) || in_array(strtolower($ext), $harmtype)) {
        return error(-3, '不允许上传此类文件');
    }
    if (!empty($limit) && $limit * 1024 < filesize($file['tmp_name'])) {
        return error(-4, "上传的文件超过大小限制，请上传小于 {$limit}k 的文件");
    }
    $result = array();
    if (empty($name) || $name == 'auto') {
        $uniacid = intval($_W['uniacid']);
        $path = "{$type}s/{$uniacid}/" . date('Y/m/');
        mkdirs(ATTACHMENT_ROOT . '/' . $path);
        $filename = file_random_name(ATTACHMENT_ROOT . '/' . $path, $ext);
        $result['path'] = $path . $filename;
    } else {
        mkdirs(dirname(ATTACHMENT_ROOT . '/' . $name));
        if (!strexists($name, $ext)) {
            $name.= '.' . $ext;
        }
        $result['path'] = $name;
    }
    $save_path = ATTACHMENT_ROOT . '/' . $result['path'];
    if (!file_move($file['tmp_name'], $save_path)) {
        return error(-1, '保存上传文件失败');
    }
    if ($type == 'image' && $compress) {
        file_image_quality($save_path, $save_path, $ext);
    }
    $result['success'] = true;
    return $result;
}
function file_random_name($dir, $ext) {
    do {
        $filename = random(30) . '.' . $ext;
    } while (file_exists($dir . $filename));
    return $filename;
}
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $res=model('core/tools')->authcode($string, $operation, $key, $expiry);
}
function reply_single($id) {
    $res = array();
    $id = intval($id);
    $res = pdo_get('rule', array('id' => $id));
    if (empty($res)) {
        return $res;
    }
    $res['keywords'] = pdo_getall('rule_keyword', array('rid' => $id));
    return $res;
}
function printer($printContent, $modulename, $printid) {
    $params = array('id' => $printid, 'sendcontent' => $printContent);
    $return = cfc('jy_print')->printer($params, $modulename);
    return $return;
}
function logging_run($log, $type = 'trace', $filename = 'run') {
    global $_W;
    $filename = IA_ROOT . '/data/logs/' . $filename . '_' . date('Ymd') . '.log';
    load()->func('file');
    mkdirs(dirname($filename));
    $logFormat = "%date %type %user %url %context";
    if (!empty($GLOBALS['_POST'])) {
        $context[] = logging_implode($GLOBALS['_POST']);
    }
    if (is_array($log)) {
        $context[] = logging_implode($log);
    } else {
        $context[] = preg_replace('/[ trn]+/', ' ', $log);
    }
    $log = str_replace(explode(' ', $logFormat), array('[' . date('Y-m-d H:i:s', $_W['timestamp']) . ']', $type, $_W['username'], $_SERVER["PHP_SELF"] . "?" . $_SERVER["QUERY_STRING"], implode("n", $context),), $logFormat);
    file_put_contents($filename, $log . "rn", FILE_APPEND);
    return true;
}
function logging_implode($array, $skip = array()) {
    $return = '';
    if (is_array($array) && !empty($array)) {
        foreach ($array as $key => $value) {
            if (empty($skip) || !in_array($key, $skip, true)) {
                if (is_array($value)) {
                    $return.= $key . '={' . logging_implode($value, $skip) . '}; ';
                } else {
                    $return.= "$key=$value; ";
                }
            }
        }
    }
    return $return;
}